package com.caidan.security.web.filter;

import com.caidan.security.domain.entity.UmsSysUser;
import com.caidan.security.web.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
//        无token 就直接放行 后面还有过滤器
        if (token == null) {
            doFilter(request, response, filterChain);
            return;
        }
//        有token 通过jwt进行解析
        Claims claims = null;
        UmsSysUser user = new UmsSysUser();

        try {
            claims = jwtUtils.parseToken(token);
            // 解析内容
            String name = claims.get("name", String.class);
            user.setUsername(name);
            UsernamePasswordAuthenticationToken ums = new UsernamePasswordAuthenticationToken(name, null, user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(ums);
//            放行
            doFilter(request,response,filterChain);
        } catch (Exception e) {
            log.error("解析token出现异常");
        }


    }
}
